package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.base.core.EmptyUtils;
import com.base.core.config.DefalutSp;
import com.base.core.net.BaseObserver;
import com.base.core.net.RxHelper;
import com.base.core.net.RxManager;
import com.base.core.ui.BaseCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import io.reactivex.functions.Consumer;

import static com.example.myapplication.AesCBC.ivParameter;
import static com.example.myapplication.AesCBC.sKey;
import static com.example.myapplication.NotificationMonitorService.allpakage;


public class LoginActivity extends AppCompatActivity {
    TextView edt_pakage;
    EditText edt_store;
    EditText edt_key;
    EditText edt_iv;
    TextView edt_post;
    EditText edt_password;
    TextView tv_login;
    TextView tv_status;
    TextView tv_packge;
    TextView tv_add;
    TextView tv_clear;
    RxManager rxManager;
    Activity mactivity;
    TextView tv_test;
    String uniqueID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        rxManager = new RxManager();
        mactivity = this;
        edt_pakage = findViewById(R.id.edt_pakage);
        edt_store = findViewById(R.id.edt_store);
        edt_post = findViewById(R.id.edt_post);
        tv_status = findViewById(R.id.tv_status);
        edt_password = findViewById(R.id.edt_password);
        tv_login = findViewById(R.id.tv_login);
        tv_packge = findViewById(R.id.tv_packge);
        tv_add = findViewById(R.id.tv_add);
        tv_clear = findViewById(R.id.tv_clear);
        tv_test = findViewById(R.id.tv_test);
        edt_key = findViewById(R.id.edt_key);
        edt_iv = findViewById(R.id.edt_iv);
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddDialog dialog = new AddDialog(mactivity);
                dialog.setCallback(new BaseCallback() {
                    @Override
                    public void response(Object object) {
                        setPackText();
                        MySp.putPacage(allpakage);
                    }
                });
                dialog.show();
            }
        });

        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.READ_PHONE_STATE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (!aBoolean) {
                   /* ToastUtils.show("请打开获取手机信息权限"
                    );*/
                    uniqueID = MyApplication.getdevicetoken(LoginActivity.this);
                } else {
                   // uniqueID = getUniqueID(LoginActivity.this);
                    uniqueID = MyApplication.getdevicetoken(LoginActivity.this);
                    Log.d("uniqueID", uniqueID);
                }
            }
        });

        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CommitDialog dialog = new CommitDialog(mactivity, "是否清空所有包名？");
                dialog.show();
                dialog.setCallback(new BaseCallback() {
                    @Override
                    public void response(Object object) {
                        dialog.dismiss();
                        ToastUtils.show("包名已经被清空");
                        allpakage.clear();
                        MySp.putPacage(allpakage);
                        setPackText();
                    }
                });

            }
        });
        String config1 = DefalutSp.getString("config");
        if (EmptyUtils.isNotEmpty(config1)) {
            Config config = new Gson().fromJson(config1, new TypeToken<Config>() {
            }.getType());
            edt_iv.setText(config.getIv());
            edt_key.setText(config.getKey());
            edt_post.setText(config.getPost());
        }

        tv_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test();
            }
        });
        allpakage.clear();
        List<String> pacage = MySp.getPacage();
        if (EmptyUtils.isNotEmpty(pacage)) {
            allpakage.addAll(pacage);
        }
        setPackText();
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .keyboardEnable(false)
                .init();
    }

    private void test() {
        if (EmptyUtils.isEmpty(uniqueID)) {
            uniqueID = MyApplication.getdevicetoken(LoginActivity.this);
        }

        String obj = edt_post.getText().toString().trim();
        if (EmptyUtils.isEmpty(obj)) {
            ToastUtils.show("请设置post地址");
            return;
        }
        Map<String, Object> json = new HashMap<>();

        json.put("name", "test");
        json.put("txt", "test");
        json.put("id", uniqueID);
        //json.put("id", 0);
        String aes_key = edt_key.getText().toString().trim();
        String aes_iv = edt_iv.getText().toString().trim();
        sKey = aes_key;
        ivParameter = aes_iv;
        if (EmptyUtils.isEmpty(aes_key)) {
            ToastUtils.show("请输入加密的key");
            return;
        }
        if (aes_key.length() < 16) {
            ToastUtils.show("加密的key为16位");
            return;
        }
        if (EmptyUtils.isEmpty(aes_iv)) {
            ToastUtils.show("请输入加密的iv");
            return;
        }
        if (aes_iv.length() < 16) {
            ToastUtils.show("加密的iv为16位");
            return;
        }
        String sSrc = new Gson().toJson(json);
        String encrypt = AesCBC.getInstance().encrypt(sSrc);
        encrypt = encrypt.replace("\\/", "/");
        Retrofit2Client.createApi(ApiInterfae.class).push(obj+ "sendMsg",
                encrypt).compose(RxHelper.rxIo())
                .subscribe(new BaseObserver<Object>(rxManager, false) {
                    @Override
                    protected void onSuccess(Object data) {
                        ToastUtils.show("发送成功,post地址有效");
                    }

                    @Override
                    protected void onFailure(String message, int code) {
                        super.onFailure(message, code);
                    }
                });
    }

    private void setPackText() {
        tv_packge.setText("已设置的包名：" + "\n");
        for (String s : allpakage) {
            tv_packge.append(s + "\n");
        }
    }

    private void login() {
        //final String pakege = "com.icbc.biz.elife";
        final String password = edt_password.getText().toString();
        final String post = edt_post.getText().toString();
        final String store = edt_store.getText().toString();
        String aes_key = edt_key.getText().toString().trim();
        String aes_iv = edt_iv.getText().toString().trim();
        if (EmptyUtils.isEmpty(allpakage)) {
            ToastUtils.show("请添加包名");
            return;
        }

        if (EmptyUtils.isEmpty(post)) {
            ToastUtils.show("请输入POST地址");
            return;
        }
        if (EmptyUtils.isEmpty(aes_key)) {
            ToastUtils.show("请输入加密的key");
            return;
        }
        if (aes_key.length() < 16) {
            ToastUtils.show("加密的key为16位");
            return;
        }
        if (EmptyUtils.isEmpty(aes_iv)) {
            ToastUtils.show("请输入加密的iv");
            return;
        }
        if (aes_iv.length() < 16) {
            ToastUtils.show("加密的iv为16位");
            return;
        }
        sKey = aes_key;
        ivParameter = aes_iv;
        try {
            String enString = AesCBC.getInstance().encrypt("{\"id\":\"test\",\"name\":\"test\"," +
                    "\"txt\":\"test\"}");
            String DeString = AesCBC.getInstance().decrypt(enString);
            Log.d("decrypt", DeString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_status.setVisibility(View.GONE);
        DefalutSp.putToken("111");
        Config config = new Config(sKey, ivParameter, post);
        DefalutSp.putString("config", new Gson().toJson(config));
        // pakage = pakege;
        ConfigBean configBean = new ConfigBean("", store, post);
        MainActivity.toMainActivity(mactivity, configBean);
        finish();

//        Map<String, Object> params = new HashMap<>();
//        params.put("packageName", pakege);
//        params.put("memberNumber", store);
//        params.put("postUrl", post);
//        params.put("password", password);
//        RetrofitClient.init("http://" + post);
//
//        RetrofitClient.createApi(ApiInterfae.class).login(params).compose(RxHelper.<Map<String,
//        String>>handleResult())
//                .subscribe(new BaseObserver<Map<String, String>>(rxManager) {
//                    @Override
//                    protected void onSuccess(Map<String, String> data) {
//                        tv_status.setVisibility(View.GONE);
//                        DefalutSp.putToken(data.get("token"));
//                        pakage = pakege;
//                        ConfigBean configBean = new ConfigBean(pakege, store, post);
//                        MainActivity.toMainActivity(mactivity, configBean);
//                        finish();
//                    }
//
//                    @Override
//                    protected void onFailure(String message, int code) {
//                        super.onFailure(message, code);
//                        tv_status.setVisibility(View.VISIBLE);
//                        tv_status.setText(message);
//
//                    }
//                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rxManager.unSubscribe();

    }
}
